/**
 * Created by FreezeSoul on 2017/7/22.
 */
'use strict';
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'pagination',
    'css!app/plugins/controls/common/pagetable/resource/pagination.css'
], function (Chart, Util, Meta, $, _, JSON, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'TABLE_IS_BORDER',
                name: '显示边框',
                enable: true,
                type: 'checked',
                value: true,
                default: true,
                link: 'hasBorder',
                tooltip: '是否显示显示边框'
            },
            {
                group: '基础',
                id: 'TABLE_BORDER_COLOR',
                name: '边框颜色',
                enable: true,
                type: 'color',
                value: '#083C62',
                default: '#083C62',
                link: 'borderColor',
                tooltip: '边框颜色'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_ARRAY',
                name: '固定表头',
                enable: false,
                type: 'text',
                value: "",
                default: "",
                link: 'headerArray',
                tooltip: '固定表头，支持多行、合并，“,”分隔，“;”多行分隔，相同表头自动合并，<br/>如：合并表头1,合并表头1,合并表头1,合并表头2,合并表头2;日期,受理警情,有效警情,无效警情,有效警情比例'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_HEIGHT',
                name: '表头行高',
                enable: false,
                type: 'number',
                value: 25,
                default: 25,
                link: 'headerHeight',
                tooltip: '表头行高,只能统一设置'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_ROW_HEIGHT',
                name: '数据行行高',
                enable: false,
                type: 'number',
                value: 25,
                default: 25,
                link: 'dataRowHeight',
                tooltip: '数据行行高,只能统一设置'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_WIDTH',
                name: '表格列列宽',
                enable: false,
                type: 'text',
                value: "1",
                default: "1",
                link: 'dataColWidth',
                tooltip: '表格列列宽,占比设置，“,”分隔，确保数量为1或与列数匹配，否则无效，如：1,1,1,1 指的是均分'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_COLOR',
                name: '表头背景颜色',
                enable: false,
                type: 'text',
                value: "#0A3555",
                default: "#0A3555",
                link: 'headerColor',
                tooltip: '表头背景颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_HEAD_FONT_COLOR',
                name: '表头字体颜色',
                enable: false,
                type: 'text',
                value: "#FFFFFF",
                default: "#FFFFFF",
                link: 'headerFontColor',
                tooltip: '表头字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_HEAD_FONT_SIZE',
                name: '表头字体大小',
                enable: false,
                type: 'number',
                value: 10,
                default: 10,
                link: 'headerFontSize',
                tooltip: '表头字体大小'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_I',
                name: '数据行背景颜色I',
                enable: false,
                type: 'text',
                value: "#0E1824",
                default: "#0E1824",
                link: 'dataRowColorI',
                tooltip: '数据行背景颜色I，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_II',
                name: '数据行背景颜色II',
                enable: false,
                type: 'text',
                value: "#0E1824",
                default: "#0E1824",
                link: 'dataRowColorII',
                tooltip: '数据行背景颜色II，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_FONT_COLOR',
                name: '数据行字体颜色',
                enable: false,
                type: 'text',
                value: "#9EE4FD",
                default: "#9EE4FD",
                link: 'dataRowFontColor',
                tooltip: '数据行字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_FONT_COLOI',
                name: '悬停数据行字体颜色',
                enable: false,
                type: 'text',
                value: "#D19910",
                default: "#D19910",
                link: 'dataRowHoverFontColor',
                tooltip: '鼠标悬停字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_IQ',
                name: '鼠标悬停首列背景颜色',
                enable: false,
                type: 'text',
                value: "#E3AC13",
                default: "#E3AC13",
                link: 'dataFirstListBackgroundColor',
                tooltip: '鼠标悬停首列背景颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_IW',
                name: '鼠标悬停首列字体颜色',
                enable: false,
                type: 'text',
                value: "#474335",
                default: "#474335",
                link: 'dataFirstListBackgroundFontColor',
                tooltip: '鼠标悬停首列字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_IS_BORDIO',
                name: '显示分页',
                enable: true,
                type: 'checked',
                value: true,
                default: true,
                link: 'showPager',
                tooltip: '是否显示显示边框'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_OO',
                name: '每页可显示数据',
                enable: false,
                type: 'number',
                value: 13,
                default: 13,
                link: 'displayDataPage',
                tooltip: '设置每页可显示多少条数据 ，默认是每页显示13条数据'

            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_FONT_SIZE',
                name: '数据行字体大小',
                enable: false,
                type: 'number',
                value: 10,
                default: 10,
                link: 'dataRowFontSize',
                tooltip: '数据行字体大小'
            },
            {
                group: '基础',
                id: 'TABLE_COLOR_SELECTOR',
                name: '颜色取色器',
                enable: true,
                type: 'color',
                value: '#FFFFFF',
                default: '#FFFFFF',
                tooltip: '颜色取色器，仅供其他颜色相关属性取色'
            },
            {
                group: '绑定',
                id: 'TABLE_BINDING',
                name: '数据绑定',
                enable: true,
                type: 'sortBinding',
                dataset: '',
                columns: [],
                tooltip: '表格数据绑定'
            },
            {
                group: '绑定',
                id: 'TABLE_DATA_COUNT',
                name: '翻页绑定',
                enable: true,
                type: 'textBinding',
                dataset: '',
                ctype: 'all',//列类型，支持 all,dimension,measure
                column: {},
                tooltip: '翻页绑定支持，总记录数，对于翻页支持，按时只支持一个控件，参数为：PageSize，OffsetRows'
            },
            {
                group: '事件',
                id: 'PageTableClickJsEval',
                name: '点击执行脚本',
                enable: false,
                type: 'script',
                value: '',
                default: '',
                link: 'clickPageTableScript',
                tooltip: '点击执行脚本，可定制复杂的JS操作,'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var table = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._clickRowData = null;
            this._container = null;
            this._pageData = null;
            this._header = [];
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    hasBorder: true,
                    borderColor: "#083C62",
                    headerHeight: 30,
                    dataRowHeight: 30,
                    headerColor: "#0A3555",
                    headerFontColor: "#FFFFFF",
                    headerFontSize: 10,
                    dataRowColorI: "#0E1824",
                    dataRowColorII: "#0E1824",
                    dataRowFontColor: "#9EE4FD",
                    dataRowHoverFontColor: "#D19910",
                    dataFirstListBackgroundColor: "#E3AC13",
                    dataFirstListBackgroundFontColor: "#474335",
                    displayDataPage: 13,
                    showPager: true,
                    dataRowFontSize: 10,
                    data: [
                        ["1", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["2", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["3", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["4", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["5", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["6", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["7", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["8", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["9", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["10", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["11", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["12", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"],
                        ["13", "TCP Flood", "项目A", "国电投", "09", "19.00", "28.68", "28.68", "预警"]
                    ],
                    headerArray: "序号,项目编号,项目名称,客户,计划吊装量,实际吊装量,物料型号,偏差,预警状态",
                    dataColWidth: "9",
                    clickPageTableScript: '',
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },

        _render: function (option) {
            //$(this._container).empty();
            var _this = this;
            //分页数据初始化
            //总条数
            var totalSizes = 0;
            var totalPage = 0;
            if (this._table) {
                $(this._table).remove();
            }
            //判断有没有总数
            if (this._pageData != null) {
                totalSizes = this._pageData[0];
                //遍历取总数的值
                for (var pro in totalSizes) {
                    if (totalSizes.hasOwnProperty(pro)) {
                        totalSizes = totalSizes[pro]
                    }
                }
                //总页数
                totalPage = totalSizes / option.displayDataPage;
                if (totalPage < 1) {
                    totalPage = 1;
                } else {
                    totalPage = Math.ceil(totalPage);
                }
            }
            var borderStr = option.hasBorder ? ("border: 2px solid " + option.borderColor + ";") : "";
            var bottom = option.showPager ? "50px" : "0";
            var tableHtml = '<div style="overflow-y:auto;width: 100%; position: absolute;top: 0;bottom: ' + bottom + ';"><table style="width:100%;' + borderStr + '">';
            var headerArrayList = [];
            var tableHeaderColCount = 0;
            if (this._header && this._header.length > 0) {
                headerArrayList = [this._header];
                tableHeaderColCount = this._header.length;
            } else {
                _.each($.trim(option.headerArray).split(";"), function (headerListStr) {
                    var headerList = $.trim(headerListStr).split(",");
                    headerArrayList.push(headerList);
                    tableHeaderColCount = headerList.length;
                });
            }
            var headerBgColors = $.trim(option.headerColor).split(',');
            var headerFontColors = $.trim(option.headerFontColor).split(',');
            var colWidthArray = $.trim(option.dataColWidth).split(',');
            var totalWidth = _.reduce(colWidthArray, function (memo, num) {
                return parseInt(memo) + parseInt(num);
            }, 0);
            var widthPercentArray = [];
            _.each(colWidthArray, function (colWidth) {
                widthPercentArray.push(Math.round(colWidth / totalWidth * 100) + "%");
            });
            _.each(headerArrayList, function (headerArray) {
                var colSpanNumber = 1;
                tableHtml += '<tr style="height:' + $.trim(option.headerHeight) + 'px;font-size: ' + $.trim(option.headerFontSize) + 'px;font-weight: bold;">';
                $.each(headerArray, function (i, headerName) {
                    var nextHeaderName = headerArray.length === (i + 1) ? "" : headerArray[i + 1];
                    if (nextHeaderName !== headerName) {
                        var bgColorStr = "";
                        if (headerBgColors.length === 1) {
                            bgColorStr = 'background-color:' + headerBgColors[0] + ";";
                        } else {
                            bgColorStr = headerBgColors.length === headerArray.length ? ('background-color:' + $.trim(headerBgColors[i]) + ';') : "";
                        }
                        var fontColorStr = "";
                        if (headerFontColors.length === 1) {
                            fontColorStr = 'color:' + headerFontColors[0] + ";";
                        } else {
                            fontColorStr = headerFontColors.length === headerArray.length ? ('color:' + $.trim(headerFontColors[i]) + ';') : "";
                        }
                        var widthPercent = "";
                        if (widthPercentArray.length === headerArray.length) {
                            widthPercent = "width:" + widthPercentArray[i] + ";"
                        }
                        var borderStr = option.hasBorder ? ("border: 1px solid " + option.borderColor + ";") : "";
                        tableHtml += '<th colspan="' + colSpanNumber + '" style="text-align: center;' + bgColorStr + fontColorStr + widthPercent + borderStr + '">' + headerName + '</th>';
                        colSpanNumber = 1;
                    } else {
                        colSpanNumber++;
                    }
                });
                tableHtml += '</tr>';
            });
            var rowBgColors = [];
            var rowBgColorsI = $.trim(option.dataRowColorI).split(',');
            var rowBgColorsII = $.trim(option.dataRowColorII).split(',');
            var rowFontColors = $.trim(option.dataRowFontColor).split(',');
            //悬停数据行字体颜色
            var rowHoverFontColors = $.trim(option.dataRowHoverFontColor).split(',');
            //鼠标悬停首列背景颜色
            var dataFirstListBackgroundColor = $.trim(option.dataFirstListBackgroundColor).split(',');
            //鼠标悬停首列字体颜色
            var dataFirstListBackgroundFontColor = $.trim(option.dataFirstListBackgroundFontColor).split(',');
            //隐藏分页
            var mapper = [];
            //this._data
            //this._option.Option.data
            $.each(this._option.Option.data, function (n, row) {
                var mouseHoverColumnId = Util.newUUID();
                mapper.push({id: mouseHoverColumnId, data: row});
                tableHtml += '<tr class="mouHoverColumnId" id=' + mouseHoverColumnId + ' style="height:' + $.trim(option.dataRowHeight) + 'px;font-size: ' + $.trim(option.dataRowFontSize) + 'px;">';
                $.each(row, function (i, col) {
                    rowBgColors = n % 2 === 0 ? rowBgColorsI : rowBgColorsII
                    var bgColorStr = "";
                    if (rowBgColors.length === 1) {
                        bgColorStr = 'background-color:' + rowBgColors[0] + ";";
                    } else {
                        bgColorStr = rowBgColors.length === tableHeaderColCount ? ('background-color:' + $.trim(rowBgColors[i]) + ';') : "";
                    }
                    var fontColorStr = "";
                    if (rowFontColors.length === 1) {
                        fontColorStr = 'color:' + rowFontColors[0] + ";";
                    } else {
                        fontColorStr = rowFontColors.length === tableHeaderColCount ? ('color:' + $.trim(rowFontColors[i]) + ';') : "";
                    }
                    if (i === 0) {
                        tableHtml += ' <td style="text-align: center;position: relative;' + bgColorStr + fontColorStr + borderStr + '"><div class="pageTableDiv1">&nbsp;</div><div class="pageTableDiv2" >' + col + '</div></td>'
                    } else {
                        tableHtml += '<td style="text-align: center;position: relative;' + bgColorStr + fontColorStr + borderStr + '">' + $('<div/>').html(col).text() + '</td>';
                    }
                });
                tableHtml += '</tr>';
            });
            tableHtml += "</table></div>";
            var $table = $(tableHtml);
            $(this._container).prepend($table)
            this._table = $table;
            //鼠标悬停样式
            $(".mouHoverColumnId").hover(function () {
                $(this).find("td  div.pageTableDiv1").css({"background-color": dataFirstListBackgroundColor});
                $(this).find("td  div.pageTableDiv2").css({
                    "background-color": dataFirstListBackgroundColor,
                    "color": dataFirstListBackgroundFontColor
                });
                $(this).find("td").css("color", rowHoverFontColors);
            }, function () {
                $(this).find("td  div.pageTableDiv1").css({"background-color": rowBgColorsII});
                $(this).find("td  div.pageTableDiv2").css({"background-color": rowBgColorsII, "color": rowFontColors});
                $(this).find('td').css("color", rowFontColors);
            }).on("click", function () {
                var id = $(this).attr("id");
                var datalist = [];
                for (var i = 0; i < mapper.length; i++) {
                    if (id === mapper[i].id) {
                        datalist = mapper[i].data
                    }
                }
                _this._clickRowData = datalist;
                if (_this._option.Option
                    && _this._option.Option.clickPageTableScript) {
                    Util.evalJavaScript(_this, _this._option.Option.clickPageTableScript);
                }
            });

            if (option.showPager) {
                if (!this._pager) {
                    var pageHtml = '<div id="pager' + Util.newUUID() + '" style="position: absolute;bottom: 0;width: 100%;"></div>';
                    var $page = $(pageHtml);
                    this._pager = $page;
                    $page.appendTo($(this._container));
                    $page.whjPaging({
                        css: 'css-2',
                        //总条数
                        totalSize: totalSizes,
                        //总页数
                        totalPage: totalPage,
                        //可选，是否展示刷新，默认true
                        isShowRefresh: false,
                        //可选，是否展示共{}页，默认true
                        isShowTotalPage: false,
                        //可选，是否展示共{}条记录，默认true
                        isShowTotalSize: false,
                        //可选，是否展示每页条数下拉框，默认true，如果设置显示，总条数必须设置
                        isShowPageSizeOpt: false,
                        //可配置选择页
                        /* pageSizeOpt: [
                            {value: option.displayDataPage, text: option.displayDataPage+'条/页', selected: true},
                            {value: 5, text: '5条/页'},
                            {value: 10, text: '10条/页'},
                            {value: 15, text: '15条/页'},
                            {value: 20, text: '20条/页'}
                          ],*/
                        callBack: function (currPage) {
                            if (_this._layout.navigate) {
                                _this._layout.navigate(_this._layout._pageId, [{
                                    ParamName: 'PageSize',
                                    ParamValue: option.displayDataPage
                                }, {
                                    ParamName: 'OffsetRows',
                                    ParamValue: (currPage - 1) * option.displayDataPage
                                }]);
                            }
                        }
                    });
                }
            }
            Util.setCommonMeta(this, this._container, this._option.Option);
            return $table;
        },
        example: function () {
            try {
                var exampleOption = $.extend(true, {}, this._option.Option);
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },

        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },

        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'sortBinding'});
            if (!bindProperty) return;
            var dataSetCode = bindProperty.dataset;
            var columns = bindProperty.columns;
            var table = data[dataSetCode];
            var tableData = [];
            var tableHeader = [];
            _.each(columns, function (binding) {
                tableHeader.push(binding.ColumnCaption);
            });
            if (table && table.length > 0) {
                $.each(table, function (j, row) {
                    var rowData = [];
                    _.each(columns, function (binding) {
                        rowData.push(row[binding.ColumnName]);
                    });
                    tableData.push(rowData);
                });
            }
            var tableHeaderProperty = _.findWhere(this._option.Extend.option, {id: 'TABLE_HEADER_ARRAY'});
            if (tableHeaderProperty.enable === false) {
                this._header = tableHeader;
            } else {
                this._header = [];
            }
            if (tableData.length > 0) {
                this._option.Option.data = tableData;
            }
            //新增textBinding（取分页总条数）
            var textProperty = _.findWhere(this._option.Extend.option, {type: 'textBinding'});
            if (!textProperty) return;
            var dataSetValue = textProperty.dataset;
            var col = textProperty.columns;
            var Count = data[dataSetValue];
            _.each(col, function (binding) {
                tableHeader.push(binding.ColumnCaption);
            });
            this._pageData = Count;
        },
        setData: function (data) {
            try {
                this._readProperty();
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                    this._readProperty();
                }
                if (this._option.Option.data && this._option.Option.data.length > 0)
                    this._element = this._render(this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).remove();
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: table,
        Property: property
    };
});